package com.gf.snoopy.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;

public class ConvertUtil {
	
	private static Logger logger = Logger.getLogger(ConvertUtil.class);

	static{
		String[] dateFormats = new String[] {"MM/dd/yyyy"}; 
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
	}
	
	public static <T> T convertJsonToBean(String jsonData,Class<T> cls){
		try{
			//URL编码里面+号会转义成空格，这里要做特殊处理
			jsonData = jsonData.replace("+", "%2B");
			JSONObject obj = JSONObject.fromObject(urlEncodeToStr(jsonData));
			T bean = (T)JSONObject.toBean(obj, cls);
			return bean;
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return null;
		}
	}
	
	public static <T> T convert(Object obj,Class<T> cls){
		if(obj==null)
			return null;
		try {
			T instance = cls.newInstance();
			BeanUtils.copyProperties(obj, instance);
			return instance;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}
	}
	
	public static <T> List<T> convertList(List sources, Class<T> cls) {
		if(CollectionUtils.isEmpty(sources)){
			return new ArrayList<T>();
		}
		List<T> dtos = new ArrayList<T>();
		for(Object source:sources){
			dtos.add(convert(source, cls));
		}
		return dtos;
	}
	
	public static String urlEncodeToStr(String urlEncodeStr) throws UnsupportedEncodingException{
		String jdata = URLDecoder.decode(urlEncodeStr, "utf-8");
		if(jdata.endsWith("=")){
			jdata = jdata.substring(0, jdata.length()-1);
		}
		return jdata;
	}
	

}
